# -*- coding: utf-8 -*-
import scrapy
from MyScrapy.items import MeituanHospital, MeituanGoods


class MeituanSpider(scrapy.Spider):
    name = 'meituan'
    proxy_list = []
    allowed_domains = ['meituan.com']
    start_urls = ['https://wh.meituan.com/s/%E5%8A%A8%E7%89%A9%E5%8C%BB%E9%99%A2/']

    def parse(self, response):
        hospital_list = response.xpath('//div[@class="list-item-desc"]')
        if not len(hospital_list):
            print('hospital_list is null')
        for hospital in hospital_list:
            item = MeituanHospital()
            item['name'] = hospital.xpath('div[@class="list-item-desc-top"]/a/text()').get('').strip()
            goods_list = hospital.xpath('div[@class="common-deal-container"]/div[@class="deal-wrapper"]/a')
            goods_array = []
            for goods in goods_list:
                detail = MeituanGoods()
                detail['name'] = goods.xpath('div[@class="deal-title"]/span/span/text()').get('').strip()
                detail['price'] = goods.xpath('div[@class="deal-info"]/span[@class="deal-price"]/text()').get('').strip()
                sales = goods.xpath('div[@class="deal-info"]/span[@class="deal-sales"]/text()').get('').strip()
                detail['sales'] = sales[2:]     # 中文'已售'长度为2
                if not len(detail['sales']):
                    detail['sales'] = goods.xpath('div[@class="deal-info"]/span[@class="deal-sales"]/text()').extract()[1]
                goods_array.append(detail)
            item['goods'] = goods_array
            yield item

